package com.qisu.command;

import com.qisu.converters.Converters;

import io.netty.channel.ChannelHandlerContext;

/**
 * 
 * @author li
 *
 */
public abstract class AbstractSinexcelCmd extends AbstractCommand {
	@Override
	protected void init() {
		super.init();
		
		fieldsList.addField("signature", new CommandFieldDef<String>(2));
		fieldsList.addField("length", new CommandFieldDef<Integer>(2));
		fieldsList.addField("version", new CommandFieldDef<Byte>(1));
		fieldsList.addField("sequence", new CommandFieldDef<Byte>(1));
		fieldsList.addField("command", new CommandFieldDef<Integer>(2, Converters.intConverter, "命令"));
	}

	private void setLength(byte[] buf) {
		int len = buf.length;

		buf[2] = (byte)(len & 0xff);
		buf[3] = (byte)((len >> 8) & 0xff);
	}

	private void setChecksum(byte[] buf) {
		int sum = 0;

		for(int i = 6, j = buf.length - 1; i < j; i++) {
			sum += buf[i];
		}

		buf[buf.length - 1] = (byte)(sum & 0xff);
	}

	protected void setCommand(byte[] buf, int cmd) {
		buf[6] = (byte)(cmd & 0xff);
		buf[7] = (byte)((cmd >> 8) & 0xff);
	}

	protected void fillData(byte[] buf, byte[] data, int pos) {
		for(int i = 0, j = data.length; i < j; i++) {
			buf[i + pos] = data[i];
		}
	}

	protected void send(ChannelHandlerContext ctx, byte[] buf) {
		setLength(buf);
		setChecksum(buf);
		if(null != ctx) {
			ctx.writeAndFlush(buf);
		}else {
			log.warn("station not found");
		} 
	}

}
